package serverdao

import (
	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gctx"
	"github.com/gogf/gf/v2/util/gconv"
	"time"
	"xr-game-server/core/constants/common"
	"xr-game-server/core/constants/db"
	"xr-game-server/core/str"
	"xr-game-server/dto/serverdto"
	"xr-game-server/entity"
)

var servers = make([]*entity.Server, common.Zero)
var serverMap = make(map[uint64]*entity.Server)

// GetAllServer 获取所有服务器
func GetAllServer() []*entity.Server {
	return servers
}

func Save(server *entity.Server) {
	g.Model(string(entity.TbServer)).Save(server)
}

func InitServer() {
	g.Model(string(entity.TbServer)).Unscoped().OrderAsc(string(db.IdName)).Scan(&servers)
	for _, server := range servers {
		serverMap[server.ID] = server
	}
}

func GetServer(id uint64) *entity.Server {
	val, ok := serverMap[id]
	if ok {
		return val
	}
	return nil
}

func UpdateClose() {
	g.Model(string(entity.TbServer)).Data(string(entity.ServerStaus), common.ServerClose).Unscoped().Where(string(entity.ServerStaus), common.ServerNormal).Update()
	g.Model(string(entity.TbServer)).Data(string(entity.ServerStaus), common.ServerClose).Unscoped().Where(g.Map{
		string(entity.ServerStaus):             common.ServerOpenTime,
		string(entity.ServerOpenTime) + " < ?": time.Now(),
	}).Update()
}

func MergeServer(mergeServer *serverdto.MergeServerReq) {
	g.Model(string(entity.TbServer)).Data(string(entity.ServerZoneId), mergeServer.ZoneId).Unscoped().Where(string(db.IdName), mergeServer.ServerIds).Update()
}

func UpdateNormal() {
	g.Model(string(entity.TbServer)).Data(string(entity.ServerStaus), common.ServerNormal).Unscoped().Where(string(entity.ServerStaus), common.ServerClose).Update()
}

func Page(req *serverdto.CMSServerReq) (total int, data []*serverdto.ServerDto) {
	data = make([]*serverdto.ServerDto, common.Zero)
	param := make([]any, common.Zero)
	sqlRet := "select ss.*,z.name zone_name from servers ss left join zones z on z.id=ss.zone_id where 1=1 "
	if req.ZoneId != nil {
		sqlRet += " and ss.zone_id=? "
		param = append(param, req.ZoneId)
	}
	sqlRet += "  order by ss.id asc limit ?,?"
	if len(param) == common.Zero {
		total, _ = g.DB().GetCount(gctx.New(), str.GetCountSQL(sqlRet))
	} else {
		total, _ = g.DB().GetCount(gctx.New(), str.GetCountSQL(sqlRet), param)
	}

	if total == common.Zero {
		return total, data
	}

	param = append(param, req.PageIndex*req.PageSize, req.PageSize)
	var list gdb.Result
	if len(param) == common.Zero {
		list, _ = g.DB().GetAll(gctx.New(), sqlRet)
	} else {
		list, _ = g.DB().GetAll(gctx.New(), sqlRet, param)
	}

	if list == nil {
		return common.Zero, data
	}
	for _, v := range list {
		val := serverdto.NewServerDto()
		gconv.Struct(v, val)
		data = append(data, val)
	}
	return total, data
}
